# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from rest_framework import serializers
from myApp.models import Server
from myApp.utils import check_ip


class ServerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Server
        fields = "__all__"

    def validate(self, attrs):
        ip_name = attrs.get("ip")  # OrderedDict([('s_name', 'spr7'), ('ip', '10.112.228.188')])
        v_ip = check_ip(ip_name)
        if not v_ip:
            raise serializers.ValidationError("IP名称不合法")
        return attrs


class UserSerializer(serializers.ModelSerializer):
    servers = serializers.PrimaryKeyRelatedField(many=True, queryset=Server.objects.all())

    class Meta:
        model = User
        fields = ("id", "username", "servers")